package util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import bean.Customer;
import bean.GoodDetails;

/**
 * 将生成xml的文档写入文件
 * @author lei
 *
 */
public class FpUtil {
	
	private static List<Customer> cusList = new ArrayList<Customer>();
	private static String path = "temp/temp.db";
	@SuppressWarnings("deprecation")
	private static String filename = (new Date().getYear()+1900)+"-"+(new Date().getMonth()+1)+"";
	
	/**
	 * 生成与导入文件文件名相同db.文件
	 */
 	public static void createFileByName(){
		String path = "temp/"+filename+".db";
		
		try {
		File f = new File(path);
		if(!f.getParentFile().exists()){
			f.getParentFile().mkdirs();
		}
		if (!f.exists()) {
			f.createNewFile();
		}
		
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 填写数据
	 */
	public static void writeData(List<Customer> newValue){
		try {
		//readData();	
		String path = "temp/"+filename+".db";
		File file=new File(path);
		String content="";
		cusList.addAll(newValue);
		BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file, true),"UTF-8"));     
		for(int i=0;i<newValue.size();i++){
		  content+=newValue.get(i).getName()+"\t"+
				  newValue.get(i).getSh()+"\t"+
				  newValue.get(i).getBillCode()+"\r\n";
		}
		/**for(int i=0;i<cusList.size();i++){
			  content+=cusList.get(i).getName()+"\t"+
					  cusList.get(i).getSh()+"\t"+
					  cusList.get(i).getBillCode()+"\r\n";
		}**/
		
		out.write(content); 
		out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 填写数据
	 */
	public static void writeDataTemp(List<Customer> newValue){
		try {
			
			File file=new File(path);
			//FileWriter w = null;
			//w = new FileWriter(file);
			String content="";
			//cusList.addAll(newValue);
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));     
			for(int i=0;i<newValue.size();i++){
				for (GoodDetails good : newValue.get(i).getGoodDetails()) {
					content+=newValue.get(i).getBillCode()+"\t"+
							newValue.get(i).getName()+"\t"+
							newValue.get(i).getSh()+"\t"+
							newValue.get(i).getSumAmount()+"\t"+
							newValue.get(i).getDisCount()+"\t"+
							newValue.get(i).getDzdh()+"\t"+
							newValue.get(i).getYhzh()+"\t"+
							newValue.get(i).getBz()+"\t"+
							newValue.get(i).getSph()+"\t"+
							newValue.get(i).getStatus()+"\t";
					content += good.getGoodCode()+"\t"+
							   good.getGoodName()+"\t"+
							   good.getStandard()+"\t"+
							   good.getDw()+"\t"+
							   good.getPrice()+"\t"+
							   good.getNum()+"\t"+
							   good.getAmount()+"\t"+
							   good.getXh()+"\t"+
							   good.getCustomer()+"\t";
					content += "\r\n";
				}
			}
			out.write(content);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 填写数据
	 */
	@SuppressWarnings("resource")
	public static List<Customer> readDataTemp(){
		List<Customer> nameList = new ArrayList<Customer>();
		try{	
			InputStream inputStream=new FileInputStream(path);
			if(inputStream.available() == 0){
				return nameList;
			}
			BufferedReader fr=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
			String data="";
			Map<String,Customer> map = new LinkedHashMap<String,Customer>();
			while((data=fr.readLine()) != null){
				String[] arr=data.split("\t");
				if(arr.length != 1){
					Customer customer = map.get(arr[0]);
					if(customer == null){
						Customer cus = new Customer();
						//当前客户第一次出现
						cus.setBillCode(arr[0]);
						cus.setName(arr[1]);
						cus.setSh(arr[2].equals("null")?null:arr[2]);
						cus.setSumAmount(arr[3]);
						cus.setDisCount(arr[4].equals("null")?null:arr[4]);
						cus.setDzdh(arr[5].equals("null")?null:arr[5]);
						cus.setYhzh(arr[6].equals("null")?null:arr[6]);
						cus.setBz(arr[7]);
						cus.setSph(arr[8]);
						cus.setStatus(arr[9].equals("null")?null:arr[9]);
						GoodDetails good = new GoodDetails();
						good.setGoodCode(arr[10]);
						good.setGoodName(arr[11]);
						good.setStandard(arr[12]);
						good.setDw(arr[13]);
						good.setPrice(arr[14]);
						good.setNum(arr[15]);
						good.setAmount(arr[16]);
						good.setXh(arr[17]);
						good.setCustomer(arr[18]);
						List<GoodDetails> goodList = new ArrayList<GoodDetails>();
						goodList.add(good);
						cus.setGoodDetails(goodList);
						map.put(arr[0], cus);
					}else{
						//当前行为其他商品行
						GoodDetails good = new GoodDetails();
						good.setGoodCode(arr[10]);
						good.setGoodName(arr[11]);
						good.setStandard(arr[12]);
						good.setDw(arr[13]);
						good.setPrice(arr[14]);
						good.setNum(arr[15]);
						good.setAmount(arr[16]);
						good.setXh(arr[17]);
						good.setCustomer(arr[18]);
						List<GoodDetails> goodDetails = customer.getGoodDetails();
						goodDetails.add(good);
						customer.setGoodDetails(goodDetails);
					}
				}
			}
			for ( String key : map.keySet()) {
				nameList.add(map.get(key));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return nameList;	
		
	}
	
	/**
	 * 读取文件内容
	 * @param name
	 * @return
	 */
	@SuppressWarnings("resource")
	public static List<String> readData() {
		List<String> nameList = new ArrayList<String>();
		try{	
			String path = "temp/"+filename+".db";
			InputStream inputStream=new FileInputStream(new File(path));
			if(inputStream.available() == 0){
				return nameList;
			}
			BufferedReader fr=new BufferedReader(new InputStreamReader(inputStream,"UTF-8"));
			String data="";
			while((data=fr.readLine()) != null){
				Customer cus = new Customer();
				String[] arr=data.split("\t");
				if(arr.length != 1){
					nameList.add(arr[2]);
					cus.setName(arr[0]);
					cus.setSh(arr[1]);
					cus.setBillCode(arr[2]);
					cusList.add(cus);
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return nameList;	
		
		}
	
	/**
	 * 单据合并
	 * @param newValue
	 * @return
	 */
	public static List<Customer> merge(List<Customer> newValue) {
		Map<String,GoodDetails> map = new HashMap<String,GoodDetails>();
		for (Customer customer : newValue) {
			for (GoodDetails good : customer.getGoodDetails()) {
				String key = good.getPrice()+good.getGoodName()+good.getStandard()+good.getDw();
				if(map.get(key) == null){
					map.put(key, good);
				}else{
					//同类合并
					//金额
					String amount = new BigDecimal(map.get(key).getAmount()).add(
							new BigDecimal(good.getAmount())).toString();
					//数量
					String num = new BigDecimal(map.get(key).getNum()).add(
							new BigDecimal(good.getNum())).toString();
					//折扣金额合并
					if("".equals(map.get(key).getDiscount().trim())){
						map.get(key).setDiscount("0");
					}
					if("".equals(good.getDiscount().trim())){
						good.setDiscount("0");
					}
					String dis = new BigDecimal(map.get(key).getDiscount()).add(
							new BigDecimal(good.getDiscount())).toString();
					good.setDiscount(dis);
					good.setAmount(amount);
					good.setNum(num);
					if(Double.parseDouble(amount) == 0){
						map.remove(key);
					}else{
						map.put(key, good);
					}
				}
			}
			List<GoodDetails> list = new ArrayList<GoodDetails>();
			for (String name : map.keySet()) {
				list.add(map.get(name));
			}
			customer.setGoodDetails(list);
			map = new HashMap<String,GoodDetails>();
		}
		return newValue;
	}
	
	/**
	 * 查看是否存在促销商品
	 * @param customer
	 * @return
	 */
	public static Customer checkPromotion(Customer customer) {
		List<GoodDetails> list = customer.getGoodDetails();
		//商品明细从高到低排序
		Collections.sort(list);
		//得出最高金额的商品
		GoodDetails maxGood = list.get(0);
		String maxAmount = maxGood.getAmount();
		int step = 0;
		BigDecimal total = new BigDecimal(0);
		for (GoodDetails good : list) {
			total = total.add( new BigDecimal(good.getAmount()));				
		}
		//商品总金额等于最高金额总数
		if(total.compareTo(new BigDecimal(maxAmount)) == 0&& maxGood.getIsPromotion()){
			BigDecimal amount = total.divide(new BigDecimal(list.size()),8,BigDecimal.ROUND_CEILING);
			for (GoodDetails goodDetails : list) {
				goodDetails.setAmount(amount.toString());
				goodDetails.setPrice(amount.divide(new BigDecimal(goodDetails.getNum()),8,BigDecimal.ROUND_HALF_UP).toString());
			}
		}else{
			//商品总金额大于需要最大商品金额时，自动分摊100到需要促销送样的商品，对应最大商品减去相对应的金额
			for (GoodDetails good : list) {
				if(good.getAmount().equals("0.0")){
					good.setAmount("100.0");
					good.setPrice(new BigDecimal(100).divide(new BigDecimal(good.getNum()), 8, BigDecimal.ROUND_HALF_UP).toString());
					step++;	
				}
			}
			//设置抵扣后的金额
			maxGood.setAmount(new BigDecimal(maxAmount).subtract(new BigDecimal(100).multiply(new BigDecimal(step))).toString());
			//设置抵扣后的单价
			maxGood.setPrice(new BigDecimal(maxGood.getAmount()).divide(new BigDecimal(maxGood.getNum()), 8, BigDecimal.ROUND_HALF_UP).toString());
			//设置后金额为负数或为仍为0
			if(new BigDecimal(maxGood.getAmount()).compareTo(new BigDecimal(0)) != 1){
				customer = null;
			}
		}
		
		return customer;
	}

	public static void writeDataTemp(Map<String, Customer> map) {
try {
			
			File file=new File(path);
			//FileWriter w = null;
			//w = new FileWriter(file);
			String content="";
			//cusList.addAll(newValue);
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"UTF-8"));     
			for(String key : map.keySet()){
				Customer cus = map.get(key);
				for (GoodDetails good : cus.getGoodDetails()) {
					content+=cus.getBillCode()+"\t"+
							cus.getName()+"\t"+
							cus.getSh()+"\t"+
							cus.getSumAmount()+"\t"+
							cus.getDisCount()+"\t"+
							cus.getDzdh()+"\t"+
							cus.getYhzh()+"\t"+
							cus.getBz()+"\t"+
							cus.getSph()+"\t"+
							cus.getStatus()+"\t";
					content += good.getGoodCode()+"\t"+
							   good.getGoodName()+"\t"+
							   good.getStandard()+"\t"+
							   good.getDw()+"\t"+
							   good.getPrice()+"\t"+
							   good.getNum()+"\t"+
							   good.getAmount()+"\t"+
							   good.getXh()+"\t"+
							   good.getCustomer()+"\t";
					content += "\r\n";
				}
			}
			out.write(content);
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
